package com.zlp.service.impl;


import com.alibaba.fastjson.JSON;
import com.zlp.chain.Handler;
import com.zlp.dto.PromoContext;
import com.zlp.dto.PromoInDTO;
import com.zlp.dto.PromoOutDTO;
import com.zlp.service.IPromotionKey;
import com.zlp.service.IPromotionStrategy;
import com.zlp.service.PromotionStrategyFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Map;
import java.util.TreeMap;

/**
 * @author: gubin
 * @date: 2022/8/10 15:00
 * @description: 秒杀
 */
@Slf4j
@Component
public class SecKillStrategy implements IPromotionStrategy, InitializingBean {

    /**
     *  秒杀处理器
     */
    private final Map<Integer, Handler> handlers = new TreeMap<>();

    @Override
    public Map<Integer, Handler> getHandlers() {

        return handlers;
    }

    @Override
    public PromoOutDTO execute(PromoInDTO promoInDTO) {
    log.info("execute req promoInDTO={}", JSON.toJSONString(promoInDTO));
        Assert.notNull(promoInDTO.getSkuDTOList(), "商品不能为空");
        try (PromoContext occ = new PromoContext()) {
            occ.setMemberId("12");
            occ.setPromoKey(promoInDTO.getPromoKey());
            occ.setPromoId(promoInDTO.getPromoId());
            occ.setSkuId(promoInDTO.getSkuId());
            // 得到具体的handle
            handlers.get(promoInDTO.getStepKey()).handle(promoInDTO);
            log.info("秒杀策略 {}", occ);
            return PromoOutDTO.builder().reqNo(occ.getReqNo()).build();
        }
    }

    /**
     *  Bean初始化之前添加SpringBean容器中
     * @see com.zlp.service.PromotionStrategyFactory
     *
     */
    @Override
    public void afterPropertiesSet() {
        PromotionStrategyFactory.register(IPromotionKey.SECKILL, this);
    }
}
